package com.iyue.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iyue.util.ValidCode;
import com.iyue.util.code.ImageCode;

/**
 * 《验证码图片》
 * 
 * @author 孙晓晔
 * @version $Id: ValidateCode.java,v 1.1 2010/10/14 17:07:14 fresh Exp $
 */
public class ValidateCode extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7754657526181688478L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String key = request.getParameter("vkey");
		if (key == null || key.length() <= 0) {
			return;
		}

		String vcode = ValidCode.getValidCode(key);
		if (vcode == null || vcode.length() <= 0) {
			return;
		}

		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		ImageCode image = new ImageCode();
		BufferedImage im = image.creatImage(vcode);

		OutputStream out = response.getOutputStream();
		ImageIO.write(im, "JPEG", out);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
